import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class Client {
	private static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII")
			.newEncoder();

	public static boolean isPureAscii(String v) {
		return asciiEncoder.canEncode(v);
	}

	public static void main(String[] args) {
		if (args.length != 3) {
			System.out
					.println("Usage: java Client <multicast_ip> <port> <6char-nick>");
			return;
		}
		MulticastSocket socket = null;
		String nick = args[2];
		if (nick.length() > 6) {
			System.out.println("Nick too long. Use maximum 6 characters");
			return;
		}
		int port = Integer.parseInt(args[1]);
		InetAddress address = null;
		System.out.println("Parsing address...");
		try {
			address = InetAddress.getByName(args[0]);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		if (!address.isMulticastAddress()) {
			System.out.println("IP must be multicast!");
			return;
		}
		System.out.println("Creating socket...");
		try {
			socket = new MulticastSocket(port);
			socket.joinGroup(address);
			socket.setLoopbackMode(false);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Listener listener = new Listener(socket, nick);
		listener.start();
		System.out.println("Reading...");
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(System.in));
		String inputMessage = null;
		try {
			inputMessage = bufferedReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		while (!inputMessage.equals("logout")) {
			if (isPureAscii(inputMessage) && inputMessage.length() <= 20) {
				Message message = new Message(nick, inputMessage);
				byte[] byteMessage = message.convertToByteArray();
				DatagramPacket packet = new DatagramPacket(byteMessage,
						byteMessage.length, address, port);
				try {
					socket.send(packet);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else if (inputMessage.length() > 20) {
				System.out
						.println("Message is too long! Maximum message size = 20");
			} else {
				System.out
						.println("Detected non-ASCII characters! Try again without them.");
			}
			try {
				inputMessage = bufferedReader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		if (!socket.isClosed()) {
			socket.close();
		}
	}
}
